package com.example.myapp;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.example.myapp.chart.ChartActivity;
import com.example.myapp.mybluetooth.BluetoothChatService;
import com.example.myapp.mybluetooth.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "Bluetooth";
    //Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    private static final int REQUEST_ENABLE_BT = 1;
    //Member object for the chat services
    private BluetoothChatService mChatService = null;
    //Array adapter for the conversation thread
    private ArrayAdapter<String> mArrayAdapter;
    private String DeviceAddress;
    //String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    //Name of the connected device
    private String mConnectedDeviceName = null;

    private Button BtnSearch,BtnDiscoverable,BtnSend,BtnDrawing,BtnSave;
    private EditText mEtSend;
    private TextView TvRead;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BtnSearch = findViewById(R.id.btn_search);
        BtnDiscoverable=findViewById(R.id.btn_discoverable);
        BtnSend = findViewById(R.id.btn_send);
        mEtSend = findViewById(R.id.et_send);
        TvRead = findViewById(R.id.tv_read);
        BtnDrawing=findViewById(R.id.btn_drawing);
        BtnSave = findViewById(R.id.btn_save);
        OnClick onClick = new OnClick();
        BtnSearch.setOnClickListener(onClick);
        BtnDiscoverable.setOnClickListener(onClick);
        BtnSend.setOnClickListener(onClick);
        BtnDrawing.setOnClickListener(onClick);
        BtnSave.setOnClickListener(onClick);
        mArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(MainActivity.this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        }else{
            // Register for broadcasts when a device is discovered.
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(receiver, filter);
        }
    }
    @Override
    public void onStart() {
        super.onStart();
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else if (mChatService == null) {
            //setupChat();
            // Initialize the BluetoothChatService to perform bluetooth connections
            mChatService = new BluetoothChatService(MainActivity.this, mHandler);
            // Initialize the buffer for outgoing messages
            mOutStringBuffer = new StringBuffer();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mChatService != null) {
            mChatService.stop();
        }
    }

    class OnClick implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn_search: //查找蓝牙设备
                    mArrayAdapter.clear();
                    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                    if(pairedDevices.size() > 0){
                        for(BluetoothDevice device:pairedDevices){
                            // 把名字和地址取出来添加到适配器中
                            mArrayAdapter.add(device.getName()+"\n"+ device.getAddress());
                        }
                    } else Log.i(TAG,"No devices have been paired");
                    doDiscovery();
                    break;
                case R.id.btn_discoverable: //使设备可以被发现
                    if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                        startActivity(discoverableIntent);
                    }
                    break;
                case R.id.btn_send:
                    String Message = mEtSend.getText().toString();
                    sendMessage(Message);
                    break;
                case R.id.btn_drawing:
                    Intent intent = new Intent(MainActivity.this, ChartActivity.class);
                    startActivity(intent);
                    break;
                case R.id.btn_save:
                    savefile(TvRead.getText().toString());
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_ENABLE_BT:
                if(resultCode == Activity.RESULT_OK) Log.i(TAG,"蓝牙已打开");
        }
    }

    private final Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constants.MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    String writeMessage = new String(writeBuf);
                    TvRead.append("Me:  " + writeMessage+"\n");
                    //mConversationArrayAdapter.add("Me:  " + writeMessage);
                    break;
                case Constants.MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    String readMessage = new String(readBuf, 0, msg.arg1);
                    TvRead.append(mConnectedDeviceName + ":  " + readMessage+"\n");
                    //mConversationArrayAdapter.add(mConnectedDeviceName + ":  " + readMessage);
                    break;
                case Constants.MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
                    Toast.makeText(MainActivity.this, "Connected to " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    break;
                case Constants.MESSAGE_TOAST:
                    Toast.makeText(MainActivity.this, msg.getData().getString(Constants.TOAST), Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void doDiscovery(){
        Log.i(TAG,"do Discovery...");
        // If we're already discovering, stop it
        if(mBluetoothAdapter.isDiscovering()){
            mBluetoothAdapter.cancelDiscovery();
        }
        // Request discover from BluetoothAdapter
        mBluetoothAdapter.startDiscovery();
        onCreateDialog();
    }

    // Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mArrayAdapter.add(device.getName()+"\n"+ device.getAddress());
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address
                Log.i(TAG,"deviceName:"+deviceName+",deviceAddress:"+deviceHardwareAddress);
            }
        }
    };

    public void onCreateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("蓝牙设备")
                .setAdapter(mArrayAdapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String info = mArrayAdapter.getItem(which);
                        DeviceAddress = info.substring(info.length()-17);
                        // Get the BluetoothDevice object
                        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(DeviceAddress);
                        // Attempt to connect to the device
                        mChatService.connect(device);
                        Log.i(TAG,"DeviceAddress:"+DeviceAddress);
                    }
                }).show();
    }

    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(MainActivity.this, "You are not connected to a device", Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            mEtSend.setText(mOutStringBuffer);
        }
    }

    private void savefile(String content){
        FileOutputStream fileOutputStream = null;
        try {
            File dir = new File(getExternalFilesDir(Environment.getExternalStorageState()),"Data");
            if(!dir.exists()){
                dir.mkdirs();
            }
            @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMddHHmmss");// 设置时间格式
            Date date = new Date(System.currentTimeMillis());//获取当前时间
            String filename = simpleDateFormat.format(date)+".txt";
            File file = new File(dir, filename);
            if(!file.exists()) {
                file.createNewFile();
                TvRead.append("文件存储路径为："+dir+File.separator+filename);
            }
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

